package cn.hl.hm.util.token;


import cn.hl.hm.util.ContextHolderUtils;
import cn.hl.hm.util.cache.RedisTools;
import cn.hl.hm.util.json.GsonUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 客户端cookie管理是否登录
 * Created by tarzan on 2017/11/6.
 */
public class TokenUtil {
    public enum PlatformEnum{
        DRIVER(1,"driverToken_"),
        MANAGE(2,"manageToken_");
        private Integer num;
        private String platformName;

        public Integer getNum() {
            return num;
        }

        public void setNum(Integer num) {
            this.num = num;
        }

        public String getPlatformName() {
            return platformName;
        }

        public void setPlatformName(String platformName) {
            this.platformName = platformName;
        }

        PlatformEnum(Integer num, String platformName) {
            this.num = num;
            this.platformName = platformName;
        }
    }
    //生成token的key
    public static String getTokenKey(PlatformEnum platformEnum){
        return platformEnum.getPlatformName()+ ContextHolderUtils.getSession().getId();
    }

    /**
     * 获取token保存的对象
     * @param tokenKey
     * @return
     */
    public static TokenBean getTokenBean(String tokenKey){
        String token=RedisTools.getInstance().getValue(tokenKey);
        if (token!=null&&token.length()>0) {
            return GsonUtils.fromJson(token, TokenBean.class);
        }
        return null;
    }


    //保存token的value
    public static void createToken(PlatformEnum platformEnum,String value){
        RedisTools.getInstance().setValue(getTokenKey(platformEnum),value);
    }

    //检验token
    public static boolean checkToken(String tokenKey){
        if(StringUtils.isNotBlank(RedisTools.getInstance().getValue(tokenKey))){
            return true;
        }
        return false;
    }

    /**
     * 清除
     * @param tokenKey
     */
    public static void cleanToken(String tokenKey){
        RedisTools.getInstance().delKey(tokenKey);
    }
}
